package cn.wsn2018.tools.util;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.model.User;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @program: tools
 * @description 匹配用户角色
 * @author: songDaisong
 * @create: 2019-12-13 20:55
 **/
public class RoleUtil {

    @Autowired
    private static UserDao userDao;

    public static final HashMap<String,String> roleHashMap=new HashMap<String,String>(){
        {
            put(CommonValue.ROLE_ADMIN,"系统管理员");
            put(CommonValue.ROLE_AUDITOR,"业务审计员");
            put(CommonValue.ROLE_OPERATOR,"操作员");
            put(CommonValue.ROLE_SYS_AUDITOR,"系统审计员");
        }
    };

    public static String getRoleName(String roleName){
        //匹配角色，都转换为小写
        if(StringUtil.isEmptyString(roleName)){
            return "";
        }
        String name = roleHashMap.get(roleName);
        return StringUtil.isEmptyString(name)?roleName:name;
    }

    public static String checkRole(String token, HttpServletRequest request,String targetRole,String targetModule) throws Exception {
        //token值，httpRequest，targetRole/targetModule：表示我们所期待的用户角色和模块
        /**
        * @Description: 用户角色校验，校验失败就直接返回，并记录日志
        * @Param: [username, token, request, targetRole,targetModule]
        * @return: java.lang.String
        * @Author: SongDaisong
        * @Date:  2020/2/4 17:19
        */
        ServletUtil.getInstance().requestOperating(request);
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        //根据token从session拿到的角色Role
        String myRole = session.getAttribute("role").toString();
        String myUsername = session.getAttribute("username").toString();

        if (StringUtil.isEmptyString(myRole)){
            //如果myRole为空，则根据用户名去查
            User user = userDao.getUserByName(myUsername);
            myRole=user.getRole();
        }

        if(!targetRole.equals(myRole)){
            //角色校验失败
            String msg = LogUtil.produceWarningMsg(CommonValue.WARNING_TYPE_1,myUsername, myRole, targetModule);
            LogUtil.produceWarningLogs(myUsername,
                    CommonValue.WARNING_TYPE_1,
                    CommonValue.WARNING_LEVEL_0,
                    targetModule,ServletUtil.getClientIp(request),msg);
            return JsonUtil.failedJson(CommonValue.JSON_ROLE_ERROR);
        } else {
            //通过角色校验
            return null;
        }

    }
}
